package com.blockchain.front.service.content.achieve;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.blockchain.common.enums.ArticleType;
import com.blockchain.common.enums.IsPass;
import com.blockchain.common.enums.NoticeType;
import com.blockchain.common.enums.QuestionType;
import com.blockchain.common.enums.Sblx;
import com.blockchain.framework.service.ServiceFactory;
import com.blockchain.framework.service.ServiceResource;
import com.blockchain.framework.service.query.ArrayParser;
import com.blockchain.framework.service.query.EmptyPageResult;
import com.blockchain.framework.service.query.ItemParser;
import com.blockchain.framework.service.query.Paging;
import com.blockchain.framework.service.query.PagingResult;
import com.blockchain.front.service.content.ContentManage;
import com.blockchain.front.service.content.entity.Advertisement;
import com.blockchain.front.service.content.entity.Article;
import com.blockchain.front.service.content.entity.FriendlyLink;
import com.blockchain.front.service.content.entity.Notice;
import com.blockchain.front.service.content.entity.QuestionEntity;
import com.blockchain.util.parser.EnumParser;
import com.blockchain.variables.P2PConst;

public class ContentManageImpl extends AbstractConteneService implements ContentManage {
	public static class AdvertisementManageFactory implements ServiceFactory<ContentManage> {

		@Override
		public ContentManage newInstance(ServiceResource serviceResource) {
			return new ContentManageImpl(serviceResource);
		}

	}

	public ContentManageImpl(ServiceResource serviceResource) {
		super(serviceResource);
	}

	@Override
	public Advertisement[] getAll(Sblx sblx) throws Throwable {
		return selectAll(getConnection(), new ArrayParser<Advertisement>() {

			@Override
			public Advertisement[] parse(ResultSet resultSet) throws SQLException {
				ArrayList<Advertisement> list = null;
				while (resultSet.next()) {
					Advertisement adv = new Advertisement();
					adv.id = resultSet.getInt(1);
					adv.title = resultSet.getString(2);
					adv.url = resultSet.getString(3);
					adv.imageCode = resultSet.getString(4);
					if (list == null) {
						list = new ArrayList<>();
					}
					list.add(adv);
				}
				return list == null || list.size() == 0 ? null : list.toArray(new Advertisement[list.size()]);
			}
		}, "SELECT F01, F03, F04, F05 FROM T5016 WHERE F11=? AND F07 <= CURRENT_TIMESTAMP() AND F08 >= CURRENT_TIMESTAMP() ORDER BY F02 DESC",
				sblx);
	}
	
	@Override
	public PagingResult<Notice> search(Paging paging) throws Throwable {
		return selectPaging(
				getConnection(),
				new ArrayParser<Notice>() {
					@Override
					public Notice[] parse(ResultSet resultSet)
							throws SQLException {
						List<Notice> list = null;
						while (resultSet.next()) {
							Notice notice = new Notice();
							notice.id = resultSet.getInt(1);
							notice.type = NoticeType.valueOf(resultSet
									.getString(2));
							notice.title = resultSet.getString(3);
							
							notice.content = resultSet.getString(4);
							notice.titleEn = resultSet.getString(7);
							notice.contentEn = resultSet.getString(8);
							notice.titleTw = resultSet.getString(9);
							notice.contentTw = resultSet.getString(10);
							notice.createtime = resultSet.getTimestamp(5);
							notice.lastTime = resultSet.getTimestamp(6);
							if (list == null) {
								list = new ArrayList<Notice>();
							}
							list.add(notice);
						}
						return list == null || list.size() == 0 ? null : list
								.toArray(new Notice[list.size()]);
					}
				},
				paging,
				"SELECT F01,F02,F05,F06,F08,F09,F10,F11,F12,F13 FROM T5015 WHERE F04=? ORDER BY F08 DESC ",
				IsPass.S);
	}

	protected static final String SELECT_ALL_SQL = "SELECT F01,F03,F06,F07,F08,F09,F11,F12,F10,F16,F17 FROM T5011 ";
	
	protected static final ArrayParser<Article> ARRAY_PARSER = new ArrayParser<Article>() {
		@Override
		public Article[] parse(ResultSet rs) throws SQLException {
			ArrayList<Article> list = null;
			while (rs.next()) {
				Article article = new Article();
				article.id = rs.getInt(1);
				article.viewTimes = rs.getInt(2);
				article.title = rs.getString(3);
				article.titleEn = rs.getString(10);
				article.titleTw = rs.getString(11);
				article.source = rs.getString(4);
				article.summary = rs.getString(5);
				article.imageCode = rs.getString(6);
				article.createtime = rs.getTimestamp(7);
				article.publishTime = rs.getTimestamp(8);
				article.creater = rs.getString(9);
				if (list == null) {
					list = new ArrayList<>();
				}
				list.add(article);
			}
			return list == null ? null : list.toArray(new Article[list.size()]);
		}
	};
		
	
	@Override
	public PagingResult<Article> search(ArticleType articleType, Paging paging)
			throws Throwable {
		if (articleType == null) {
			return new EmptyPageResult<Article>();
		}
		StringBuilder sql = new StringBuilder(SELECT_ALL_SQL);
		sql.append(" WHERE F05 = ?  AND F02 = ? ");
		sql.append("ORDER BY F12 DESC,F04 DESC");
		PagingResult<Article> pr = selectPaging(getConnection(), ARRAY_PARSER,
				paging, sql.toString(), IsPass.S.name(),
				articleType);
		if (pr != null&&pr.getItems()!=null) {
			for (Article a : pr.getItems()) {
				String c = getCreater(Integer.parseInt(a.creater));
				a.creater = c;
			}
		}

		return pr;
	}
	

	private String getCreater(int creater) throws Throwable {
		try {
			try (Connection connection = getConnection(P2PConst.DB_CONSOLE);
					PreparedStatement pstmt = connection
							.prepareStatement("SELECT F02 FROM T7011 WHERE F01=?")) {
				pstmt.setInt(1, creater);
				try (ResultSet resultSet = pstmt.executeQuery()) {
					if (resultSet.next()) {
						return resultSet.getString(1);
					}
				}
			}
		} catch (Exception e) {

		}
		return "";
	}
	
	@Override
	public FriendlyLink[] getAll() throws Throwable {
		return selectAll(getConnection(), new ArrayParser<FriendlyLink>() {

			@Override
			public FriendlyLink[] parse(ResultSet resultSet)
					throws SQLException {
				ArrayList<FriendlyLink> list = null;
				while (resultSet.next()) {
					FriendlyLink friendlyLink = new FriendlyLink();
					friendlyLink.id = resultSet.getInt(1);
					friendlyLink.name = resultSet.getString(2);
					friendlyLink.url = resultSet.getString(3);
					friendlyLink.nameEn = resultSet.getString(4);
					friendlyLink.nameTw = resultSet.getString(5);
					if (list == null) {
						list = new ArrayList<>();
					}
					list.add(friendlyLink);
				}
				return list == null || list.size() == 0 ? null : list
						.toArray(new FriendlyLink[list.size()]);
			}
		}, "SELECT F01,F04,F05,F09,F10 FROM T5014 ORDER BY F03 DESC");
	}	
	
	@Override
	public Notice get(final int id) throws Throwable {
		if (id <= 0) {
			return null;
		}
		return select(getConnection(), new ItemParser<Notice>() {
			@Override
			public Notice parse(ResultSet resultSet) throws SQLException {
				Notice notice = null;
				if (resultSet.next()) {
					notice = new Notice();
					notice.id = id;
					notice.type = NoticeType.valueOf(resultSet.getString(1));
					notice.title = resultSet.getString(2);
					notice.content = resultSet.getString(3);
					notice.titleEn = resultSet.getString(6);
					notice.contentEn = resultSet.getString(7);
					notice.titleTw = resultSet.getString(8);
					notice.contentTw = resultSet.getString(9);
					notice.createtime = resultSet.getTimestamp(4);
					notice.lastTime = resultSet.getTimestamp(5);
				}
				return notice;
			}
		}, "SELECT F02,F05,F06,F08,F09,F10,F11,F12,F13 FROM T5015 WHERE F01 = ? ",
				id);

	}
	@Override
	public void view(int id) throws Throwable {
		if (id <= 0) {
			return;
		}
		execute(getConnection(),
				"UPDATE T5015 SET F03 = F03 + 1 WHERE F01 = ? AND F04 = ?", id,
				IsPass.S);

	}

	@Override
	public  PagingResult<QuestionEntity> search(QuestionType qtype,Paging paging) throws Throwable {
		StringBuffer s = new StringBuffer();
		ArrayList<Object> parameters = new ArrayList<Object>();
		s.append("SELECT F01,F02,F03,F04,F08,F09 FROM T5022 WHERE F02=?  ");
		parameters.add(qtype);
		s.append("ORDER BY T5022.F07 ASC,T5022.F04 DESC");
		return selectPaging(getConnection(P2PConst.DB_INFORMATION), new ArrayParser<QuestionEntity>() {
			ArrayList<QuestionEntity> list = new ArrayList<QuestionEntity>();
			@Override
			public QuestionEntity[] parse(ResultSet re) throws SQLException {
				while (re.next()) {
					QuestionEntity sc = new QuestionEntity();
					sc.id = re.getInt(1);
					sc.qt= EnumParser.parse(QuestionType.class, re.getString(2));
					sc.question = re.getString(3);
					sc.questionEn = re.getString(5);
					sc.questionTw = re.getString(6);
					sc.tjsj = re.getTimestamp(4);
					list.add(sc);
				}
				return list == null || list.size() == 0 ? null : list.toArray(new QuestionEntity[list.size()]);
			}
		},paging,s.toString(),parameters);
	}
	
	@Override
	public QuestionEntity getCjwt(int id) throws Throwable {
		StringBuffer s = new StringBuffer();
		s.append("SELECT T5022_1.F01 id,t5022_1.F02 hd, T5022.F03 wt,T5022.F02 lx,T5022.F04 sj,T5022.F08 wten,t5022_1.F03 hden,T5022.F09 wntw,t5022_1.F04 hdtw FROM T5022_1  ");
		s.append("LEFT JOIN T5022 ON T5022_1.F01 = t5022.F01 ");
		s.append("WHERE T5022.F01 = ? ");
		return select(getConnection(P2PConst.DB_INFORMATION), new ItemParser<QuestionEntity>() {
			@Override
			public QuestionEntity parse(ResultSet re) throws SQLException {
				QuestionEntity sc = new QuestionEntity();
				if (re.next()) {
					sc.id = re.getInt(1);
					sc.question = re.getString(3);
					sc.hd = re.getString(2);
					sc.questionEn = re.getString(6);
					sc.hdEn = re.getString(7);
					sc.questionTw = re.getString(8);
					sc.hdTw = re.getString(9);
					sc.qt= EnumParser.parse(QuestionType.class, re.getString(4));
					sc.tjsj=re.getTimestamp(5);
				}
				return sc;
			}
		},s.toString(),id);
	}
}
